// ZENrs 网络抽象层
// 定义统一的网络接口，用于适配多系统的网络驱动和协议栈

use std::sync::{Arc, RwLock, Mutex};
use std::collections::HashMap;

// 网络地址结构
#[repr(C)]
pub struct SocketAddress {
    pub family: u16,
    pub port: u16,
    pub address: [u8; 16], // 支持IPv4和IPv6
    pub padding: [u8; 8],  // 对齐使用
}

// Socket句柄类型
type SocketHandle = u64;

// 网络适配器接口
pub trait NetworkAdapter: Send + Sync {
    // 获取适配器名称
    fn name(&self) -> &str;
    
    // 获取MAC地址
    fn mac_address(&self) -> [u8; 6];
    
    // 获取MTU值
    fn mtu(&self) -> u16;
    
    // 启用网络接口
    fn up(&self) -> Result<(), String>;
    
    // 禁用网络接口
    fn down(&self) -> Result<(), String>;
    
    // 发送数据帧
    fn send_frame(&self, frame: &[u8]) -> Result<usize, String>;
    
    // 接收数据帧
    fn recv_frame(&self, buffer: &mut [u8]) -> Result<usize, String>;
    
    // 获取接口统计信息
    fn get_stats(&self) -> Result<NetworkStats, String>;
    
    // 设置接口参数
    fn set_param(&self, param: &str, value: &str) -> Result<(), String>;
}

// 网络统计信息结构
#[derive(Clone)]
pub struct NetworkStats {
    pub rx_packets: u64,
    pub tx_packets: u64,
    pub rx_bytes: u64,
    pub tx_bytes: u64,
    pub rx_errors: u64,
    pub tx_errors: u64,
    pub collisions: u64,
}

// 网络协议栈接口
pub trait NetworkProtocolStack: Send + Sync {
    // 获取协议栈名称
    fn name(&self) -> &str;
    
    // 初始化协议栈
    fn initialize(&self) -> Result<(), String>;
    
    // 关闭协议栈
    fn shutdown(&self) -> Result<(), String>;
    
    // 创建Socket
    fn create_socket(&self, domain: i32, socket_type: i32, protocol: i32) -> Result<SocketHandle, String>;
    
    // 关闭Socket
    fn close_socket(&self, socket: SocketHandle) -> Result<(), String>;
    
    // 绑定Socket
    fn socket_bind(&self, socket: SocketHandle, address: &SocketAddress) -> Result<(), String>;
    
    // 连接Socket
    fn socket_connect(&self, socket: SocketHandle, address: &SocketAddress) -> Result<(), String>;
    
    // 监听连接
    fn socket_listen(&self, socket: SocketHandle, backlog: i32) -> Result<(), String>;
    
    // 接受连接
    fn socket_accept(&self, socket: SocketHandle, address: Option<&mut SocketAddress>) -> Result<SocketHandle, String>;
    
    // 发送数据
    fn socket_send(&self, socket: SocketHandle, data: &[u8], flags: i32) -> Result<usize, String>;
    
    // 接收数据
    fn socket_recv(&self, socket: SocketHandle, buffer: &mut [u8], flags: i32) -> Result<usize, String>;
    
    // 发送到指定地址
    fn socket_sendto(&self, socket: SocketHandle, data: &[u8], flags: i32, address: &SocketAddress) -> Result<usize, String>;
    
    // 从指定地址接收
    fn socket_recvfrom(&self, socket: SocketHandle, buffer: &mut [u8], flags: i32, address: Option<&mut SocketAddress>) -> Result<usize, String>;
    
    // 设置Socket选项
    fn socket_setsockopt(&self, socket: SocketHandle, level: i32, optname: i32, optval: &[u8]) -> Result<(), String>;
    
    // 获取Socket选项
    fn socket_getsockopt(&self, socket: SocketHandle, level: i32, optname: i32, optval: &mut [u8]) -> Result<usize, String>;
    
    // 获取Socket地址
    fn socket_getsockname(&self, socket: SocketHandle, address: &mut SocketAddress) -> Result<(), String>;
    
    // 获取对等方地址
    fn socket_getpeername(&self, socket: SocketHandle, address: &mut SocketAddress) -> Result<(), String>;
}

// 网络管理器
pub struct NetworkManager {
    adapters: Arc<RwLock<HashMap<String, Arc<dyn NetworkAdapter>>>>,
    protocol_stacks: Arc<RwLock<HashMap<String, Arc<dyn NetworkProtocolStack>>>>,
    default_stack: Arc<RwLock<String>>,
    device_to_adapter: Arc<Mutex<HashMap<u64, String>>>,
}

impl NetworkManager {
    // 创建新的网络管理器
    pub fn new() -> Self {
        Self {
            adapters: Arc::new(RwLock::new(HashMap::new())),
            protocol_stacks: Arc::new(RwLock::new(HashMap::new())),
            default_stack: Arc::new(RwLock::new(String::new())),
            device_to_adapter: Arc::new(Mutex::new(HashMap::new())),
        }
    }
    
    // 注册网络适配器
    pub fn register_adapter(&self, adapter: Box<dyn NetworkAdapter>) -> Result<(), String> {
        let name = adapter.name().to_string();
        
        if self.adapters.read().unwrap().contains_key(&name) {
            return Err(format!("Adapter {} already exists", name));
        }
        
        // 将Box转换为Arc，并添加明确的类型标注
        let adapter_arc: Arc<dyn NetworkAdapter> = Arc::from(adapter);
        self.adapters.write().unwrap().insert(name.clone(), adapter_arc.clone());
        
        // 尝试启用新添加的适配器
        adapter_arc.up()?;
        
        Ok(())
    }
    
    // 注销网络适配器
    pub fn unregister_adapter(&self, name: &str) -> Result<(), String> {
        if let Some(adapter) = self.adapters.read().unwrap().get(name) {
            adapter.down()?;
        }
        
        self.adapters.write().unwrap().remove(name);
        
        // 清理设备映射
        let mut device_map = self.device_to_adapter.lock().unwrap();
        device_map.retain(|_, v| v != name);
        
        Ok(())
    }
    
    // 获取网络适配器
    pub fn get_adapter(&self, _name: &str) -> Option<Box<dyn NetworkAdapter>> {
        // 在实际实现中，这里应该根据名称查找适配器
        None
    }
    
    // 列出所有网络适配器
    pub fn list_adapters(&self) -> Vec<String> {
        self.adapters.read().unwrap().keys().cloned().collect()
    }
    
    // 注册协议栈
    pub fn register_protocol_stack(&self, stack: Box<dyn NetworkProtocolStack>) -> Result<(), String> {
        let name = stack.name().to_string();
        
        if self.protocol_stacks.read().unwrap().contains_key(&name) {
            return Err(format!("Protocol stack {} already exists", name));
        }
        
        // 将Box转换为Arc，并添加明确的类型标注
        let stack_arc: Arc<dyn NetworkProtocolStack> = Arc::from(stack);
        // 初始化协议栈
        stack_arc.initialize()?;
        
        self.protocol_stacks.write().unwrap().insert(name.clone(), stack_arc);
        
        // 如果这是第一个注册的协议栈，设为默认
        if self.default_stack.read().unwrap().is_empty() {
            *self.default_stack.write().unwrap() = name;
        }
        
        Ok(())
    }
    
    // 注销协议栈
    pub fn unregister_protocol_stack(&self, name: &str) -> Result<(), String> {
        // 检查是否为默认协议栈
        if *self.default_stack.read().unwrap() == name {
            // 如果还有其他协议栈，选择第一个作为默认
            let stacks = self.protocol_stacks.read().unwrap();
            let first_stack = stacks.keys().find(|&k| k != name).cloned();
            
            if let Some(new_default) = first_stack {
                *self.default_stack.write().unwrap() = new_default;
            } else {
                *self.default_stack.write().unwrap() = String::new();
            }
        }
        
        if let Some(stack) = self.protocol_stacks.read().unwrap().get(name) {
            stack.shutdown()?;
        }
        
        self.protocol_stacks.write().unwrap().remove(name);
        
        Ok(())
    }
    
    // 获取协议栈
    pub fn get_protocol_stack(&self, name: &str) -> Option<Arc<dyn NetworkProtocolStack>> {
        // 返回Arc的克隆
        self.protocol_stacks.read().unwrap().get(name).cloned()
    }
    
    // 获取默认协议栈
    pub fn get_default_protocol_stack(&self) -> Option<Arc<dyn NetworkProtocolStack>> {
        let default_name = self.default_stack.read().unwrap();
        if default_name.is_empty() {
            None
        } else {
            self.get_protocol_stack(&default_name)
        }
    }
    
    // 设置默认协议栈
    pub fn set_default_protocol_stack(&self, name: &str) -> Result<(), String> {
        if !self.protocol_stacks.read().unwrap().contains_key(name) {
            return Err(format!("Protocol stack {} not found", name));
        }
        
        *self.default_stack.write().unwrap() = name.to_string();
        Ok(())
    }
    
    // 列出所有协议栈
    pub fn list_protocol_stacks(&self) -> Vec<String> {
        self.protocol_stacks.read().unwrap().keys().cloned().collect()
    }
    
    // 注册设备到适配器的映射
    pub fn register_device_adapter_mapping(&self, device_id: u64, adapter_name: &str) {
        self.device_to_adapter.lock().unwrap().insert(device_id, adapter_name.to_string());
    }
    
    // 根据设备ID获取适配器
    pub fn get_adapter_by_device_id(&self, device_id: u64) -> Option<Arc<dyn NetworkAdapter>> {
        let adapter_name_opt = {
            let device_map = self.device_to_adapter.lock().unwrap();
            device_map.get(&device_id).cloned()
        };
        
        if let Some(adapter_name) = adapter_name_opt {
            self.adapters.read().unwrap().get(&adapter_name).cloned()
        } else {
            None
        }
    }
}

// 全局网络管理器实例
lazy_static::lazy_static! {
    pub static ref NETWORK_MANAGER: NetworkManager = NetworkManager::new();
}

// 网络错误类型
#[derive(Debug, Clone)]
pub enum NetworkError {
    NotFound,
    AlreadyExists,
    NotSupported,
    InvalidArgument,
    IoError,
    ConnectionError,
    Timeout,
    Other(String),
}

impl std::fmt::Display for NetworkError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            NetworkError::NotFound => write!(f, "Network resource not found"),
            NetworkError::AlreadyExists => write!(f, "Network resource already exists"),
            NetworkError::NotSupported => write!(f, "Operation not supported"),
            NetworkError::InvalidArgument => write!(f, "Invalid argument"),
            NetworkError::IoError => write!(f, "I/O error"),
            NetworkError::ConnectionError => write!(f, "Connection error"),
            NetworkError::Timeout => write!(f, "Operation timed out"),
            NetworkError::Other(msg) => write!(f, "{}", msg),
        }
    }
}

impl std::error::Error for NetworkError {}

// 将标准库的Result转换为网络Result
type NetworkResult<T> = Result<T, NetworkError>;

// 辅助函数：从字符串创建SocketAddress
pub fn socket_address_from_string(family: u16, address_str: &str, port: u16) -> Result<SocketAddress, String> {
    let mut address = [0u8; 16];
    
    if family == 2 { // AF_INET
        // 解析IPv4地址
        let parts: Vec<&str> = address_str.split('.').collect();
        if parts.len() != 4 {
            return Err("Invalid IPv4 address".to_string());
        }
        
        for (i, part) in parts.iter().enumerate() {
            if let Ok(num) = part.parse::<u8>() {
                address[i] = num;
            } else {
                return Err("Invalid IPv4 address".to_string());
            }
        }
    } else if family == 10 { // AF_INET6
        // 解析IPv6地址（简化实现）
        // 实际实现应该使用适当的IPv6地址解析库
        return Err("IPv6 address parsing not implemented".to_string());
    } else {
        return Err("Unsupported address family".to_string());
    }
    
    Ok(SocketAddress {
        family,
        port,
        address,
        padding: [0u8; 8],
    })
}